package com.tang.common.utils.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.fasterxml.jackson.annotation.JsonFormat;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeConverter implements Converter<LocalDateTime> {



    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    @Override
    public LocalDateTime convertToJavaData(ReadConverterContext<?> context) throws Exception {
        String format = context.getContentProperty().getField().getAnnotation(JsonFormat.class).pattern();
        return LocalDateTime.parse(context.getReadCellData().getStringValue(), DateTimeFormatter.ofPattern(format));
    }


    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<LocalDateTime> context) throws Exception {
        String format = context.getContentProperty().getField().getAnnotation(JsonFormat.class).pattern();
        return new WriteCellData<>(context.getValue().format(DateTimeFormatter.ofPattern(format)));
    }
}
